﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.IO;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Xml;
using SEO.Entity;
using SEO.Business;
using System.Net;
using System.Text;
using System.IO.Compression;
using System.Data;

/// <summary>
///Common 的摘要说明
/// </summary>
public static class Common
{
    #region MD5加密
    /// <summary>
    /// MD5加密
    /// </summary>
    /// <param name="strValue"></param>
    /// <returns></returns>
    public static string md5(string strValue)
    {
        byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(strValue);
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        byte[] result = md5.ComputeHash(bytValue);
        string strmd5 = "";
        for (int i = 0; i < result.Length; ++i)
        {
            byte bValue = result[i];
            strmd5 += bValue.ToString("x2");
        }
        return strmd5.ToUpper();
    }
    #endregion

    #region 获取页面参数
    /// <summary>
    /// 获取页面参数
    /// </summary>
    /// <param name="param">参数名称</param>
    /// <param name="type">类型(1：post,0：get)</param>
    /// <returns>参数值</returns>
    public static string GetQueryValue(string param, int type)
    {
        string result;
        if (type == 1 && HttpContext.Current.Request.Form[param] != null)
        {
            //  POST 方式可以取到数据
            result = HttpContext.Current.Request.Form[param].Trim();
        }
        else if (type == 0 && HttpContext.Current.Request.QueryString[param] != null)
        {
            //  POST 方式取不到，但GET方式可以取到数据
            result = HttpContext.Current.Request.QueryString[param].Trim();
        }
        else
        {
            //  都取不到数据
            result = string.Empty;
        }
        return result;
    }
    #endregion

    #region 登记日志
    /// <summary>
    /// 登记日志
    /// </summary>
    /// <param name="info"></param>
    public static void Log(string info)
    {
        try
        {
            if (HttpContext.Current != null)
            {
                HttpContext.Current.Application.Lock();
                string file = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["LogFile"] + "\\" + DateTime.Now.ToString("yyyy"));
                if (!Directory.Exists(file))
                {
                    Directory.CreateDirectory(file);
                }
                file += "\\" + DateTime.Now.ToString("yyyyMMdd") + ".log";
                StreamWriter sw = new StreamWriter(file, true, System.Text.Encoding.UTF8);
                sw.WriteLine(string.Format("{0} --- {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), info));
                sw.Close();
                HttpContext.Current.Application.UnLock();
            }
        }
        catch { }
    }
    #endregion

    #region 获取访客真实IP
    /// <summary>
    /// 获取访客真实IP
    /// </summary>
    /// <returns></returns>
    public static string GetVistorsIP()
    {
        //获取代理IP
        string strIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (string.IsNullOrEmpty(strIP))
        {
            //无代理获取访客真正IP
            strIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }
        else
        {
            //有代理，每一个IP为访客真正IP
            if (strIP.IndexOf(',') > -1)
            {
                strIP = strIP.Substring(0, strIP.IndexOf(','));
            }
            if (strIP.IndexOf(';') > -1)
            {
                strIP = strIP.Substring(0, strIP.IndexOf(';'));
            }
        }
        string Reg = @"([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})";
        Regex regex = new Regex(Reg);
        if (string.IsNullOrEmpty(strIP) || !regex.IsMatch(strIP))
        {
            strIP = HttpContext.Current.Request.UserHostAddress;
        }

        if (string.IsNullOrEmpty(strIP) || !regex.IsMatch(strIP))
        {
            strIP = "0.0.0.0";
        }
        return strIP.Trim();

    }
    #endregion

    #region 获取域名后缀
    public static List<string> DomainList = null;
    /// <summary>
    /// 获取域名后缀列表
    /// </summary>
    /// <returns></returns>
    public static List<string> GetDomainList()
    {
        if (DomainList == null)
        {
            DomainList = new List<string>();
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["DomainXml"]));
                XmlNodeList nodeList = xmlDoc.SelectNodes("root/tldns/tldn");
                foreach (XmlNode nodeItem in nodeList)
                {
                    DomainList.Add(nodeItem.InnerText.Trim());
                }
            }
            catch (Exception ex)
            {
                Log("加载域名后缀xml出错：" + ex.Message);
            }
        }
        return DomainList;
    }

    /// <summary>
    /// 根据域名获取顶级域名
    /// </summary>
    /// <param name="strDomain"></param>
    /// <returns></returns>
    public static string GetLastDomain(string strDomain)
    {
        string lowerDomainName = strDomain.ToLower();
        if (lowerDomainName.IndexOf("http://") == 0)
            lowerDomainName = lowerDomainName.Substring(7, lowerDomainName.Length - 7);
        string[] temPart = lowerDomainName.Split('/');
        lowerDomainName = temPart[0];
        if (lowerDomainName.IndexOf("wwww.") == 0)
            lowerDomainName = lowerDomainName.Substring(5, lowerDomainName.Length - 5);
        return lowerDomainName;
    }

    /// <summary>
    /// 根据域名获取顶级域名
    /// </summary>
    /// <param name="strDomain"></param>
    /// <returns></returns>
    public static string GetTopDomain(string strDomain)
    {
        string lowerDomainName = strDomain.ToLower();
        if (lowerDomainName.IndexOf("http://") == 0)
            lowerDomainName = lowerDomainName.Substring(7, lowerDomainName.Length - 7);
        List<string> SelectDomainList = GetDomainList();
        if (SelectDomainList != null)
        {
            string[] temPart = lowerDomainName.Split('/');
            if (temPart.Length > 0)
            {
                lowerDomainName = temPart[0];
                int index = lowerDomainName.IndexOf('.');
                string tempTopDomainName = lowerDomainName;
                string domainPart = String.Empty;

                if (index > 0)
                {
                    bool bTag = false;
                    do
                    {
                        tempTopDomainName = tempTopDomainName.Substring(index, tempTopDomainName.Length - index);
                        foreach (string strSelectDomain in SelectDomainList)
                        {
                            if (tempTopDomainName == strSelectDomain)
                            {
                                domainPart = strSelectDomain;
                                bTag = true;
                                break;
                            }
                        }
                        if (bTag)
                            break;
                        tempTopDomainName = tempTopDomainName.Substring(1, tempTopDomainName.Length - 1);
                        index = tempTopDomainName.IndexOf('.');
                    } while (index > 0);
                    if (!String.IsNullOrEmpty(domainPart))
                    {
                        string namePart = lowerDomainName.Remove(lowerDomainName.Length - domainPart.Length);
                        index = namePart.LastIndexOf('.');
                        if (index > 0)
                        {
                            namePart = namePart.Substring(index + 1, namePart.Length - index - 1);
                        }
                        return namePart + domainPart;
                    }
                }
            }
        }
        return lowerDomainName;
    }
    #endregion

    #region 获取系统配置信息
    public static SysConfig sysConfig = null;
    /// <summary>
    /// 获取系统配置信息
    /// </summary>
    /// <returns></returns>
    public static SysConfig GetSysConfig()
    {
        if (sysConfig == null)
        {
            sysConfig = new BisSysConfig().GetSysConfig();
        }
        return sysConfig;
    }
    #endregion

    /// <summary>
    /// 获取截止日期
    /// </summary>
    /// <returns></returns>
    public static DateTime GetAccountDay(SysConfig info)
    {
        DateTime dDateTime = DateTime.Now;
        int nMonth = 0;
        int nYear = dDateTime.Year;
        if (dDateTime.Day < info.AccountDay.Value)
        {
            nMonth = dDateTime.AddMonths(-1).Month;
        }
        else
        {
            nMonth = dDateTime.Month;
        }
        if (nMonth == 12 && dDateTime.Month == 1)
            nYear--;
        return Convert.ToDateTime(string.Format("{0}-{1}-{2}", nYear, nMonth, info.AccountDay.Value));
    }



    /// <summary>
    /// 获取结算时间
    /// </summary>
    /// <param name="dBeginTime"></param>
    /// <param name="nAccountDay"></param>
    /// <returns></returns>
    public static DateTime GetEndTime(DateTime dBeginTime, int nAccountDay)
    {
        int nMonth = 0;
        int nYear = dBeginTime.Year;
        if (dBeginTime.Day < nAccountDay)
        {
            nMonth = dBeginTime.Month;
        }
        else
        {
            nMonth = dBeginTime.AddMonths(1).Month;
        }
        if (dBeginTime.Month == 12 && nMonth == 1)
            nYear++;
        return Convert.ToDateTime(string.Format("{0}-{1}-{2}", nYear, nMonth, nAccountDay));


    }

    /// <summary>
    /// 验证网址是否新闻源
    /// </summary>
    /// <param name="strUrl"></param>
    /// <returns></returns>
    public static int CheckNewsWeb(string strUrl)
    {
        //获取文章类型
        BisNewsWeb bisInfo = new BisNewsWeb();
        string strTopDomain = Common.GetTopDomain(strUrl);
        int nAimID = bisInfo.GetNewsWebID(strTopDomain, true);
        if (nAimID == 0)
        {
            if (strUrl.ToLower().IndexOf("http://wwww.") < 0)
            {
                strTopDomain = Common.GetLastDomain(strUrl);
                nAimID = bisInfo.GetNewsWebID(strTopDomain, true);
            }
        }
        return nAimID;
    }  
}